package cn.aitstone.basic.interceptor;

import cn.aitstone.basic.annotation.PreAuthorize;
import cn.aitstone.basic.jwt.JwtUtils;
import cn.aitstone.basic.jwt.Payload;
import cn.aitstone.basic.jwt.RsaUtils;
import cn.aitstone.basic.jwt.UserInfo;
import cn.aitstone.system.mapper.PermissionMapper;
import cn.aitstone.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;

/**
 * @Description: 登录拦截器
 * @Author: Sheldon
 * @Version: 1.0
 * @Date:  2022/7/7 16:18
 */
@Component // 需要加上此注解将当前登录拦截器交给spring管理
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;

    @Value("${jwt.rsa.pub}")
    private String jwtRsaPub;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("444444444444");
        // 获取前端请求头中的token信息
        String token = request.getHeader("token");
        // 设置编码字符集
        response.setCharacterEncoding("UTF-8");
        // 设置响应参数类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        // 判断前端请求是否携带token，如果携带那么进入判断
        if(token != null){
            // 解析token得到载荷数据
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(jwtRsaPub).getFile());
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);

            /*// 根据token获取到Redis中的用户信息
            Object logininfo = redisTemplate.opsForValue().get(token);
            // 如果用户信息不为空，那么刷新Redis中token有效期*/
            if(payload != null){
                // 判断是否是后台用户，如果是进入判断
                UserInfo userInfo = payload.getUserInfo();
                Logininfo logininfo = userInfo.getLogininfo();
                if (logininfo.getType() == 0){
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                    if (preAuthorize != null){
                        String sn = preAuthorize.sn();
                        if (!userInfo.getPermissions().contains(sn)){
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
                            // 刷新、关流
                            writer.flush();
                            writer.close();
                            return false;
                        }

                    }
                }
                return true;
            }
        }
        // 获取到打印流,并设置响应数据
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
        // 刷新、关流
        writer.flush();
        writer.close();
        return false;
    }
}